﻿using Abp.UI;
using AngleSharp;
using AngleSharp.Dom;
using Camc.Quality.Dto.ProcessesEntityDto;
using Camc.Quality.Quality.Form;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Camc.Quality.Quality.TransformHtml
{
	public static class HtmlToDB
	{
		/// <summary>
		/// 读工序接口
		/// </summary>
		/// <param name="html"></param>
		/// <param name="outprocessInfoList"></param>
		/// <returns></returns>
		public static void ConvertProcessListFromHtml(string html, ref List<ProcessesDto> outprocessInfoList)
		{
            var context = BrowsingContext.New();

            var document = context.OpenAsync(r => r.Content(html)).Result;
            var processlist = outprocessInfoList;

            //Do something with LINQ
            //var processcontent = document.All.Where(m => processlist.Any(t => t.OriginalProcessesId == m.Id));
            //if (processcontent.Count() != processlist.Count())
            //{
            //    throw new UserFriendlyException("该文件记录的工序数量与PPS系统中不符！");
            //}
            foreach (var p in outprocessInfoList)
            {
                //var processinfo = outprocessInfoList.Where(t => t.OriginalProcessesId == p.Id).FirstOrDefault();
                //var process = document.CreateElement("process");
                //process.TextContent = processinfo.Id.ToString();
                //p.Insert(AdjacentPosition.BeforeBegin, process.ToHtml());
                //p.Remove();
                //p.F_HtmlContent = p.ToHtml();
            }
            //return document.ToHtml();
        }

        /// <summary>
        /// 转换html分析出表内容
        /// </summary>
        /// <param name="htmlString"></param>
        /// <param name="tableHtmlList"></param>
        /// <returns></returns>
        public static string ConvertHtml(int processesSequence, string htmlString, string techniqueName, List<string> tableClassNameList, bool getWokrStep, ref Dictionary<string, string> tableHtmlList)
        {
            var context = BrowsingContext.New();
            var document = context.OpenAsync(req => req.Content(htmlString)).Result;
            var tableLabListItemsLinq = document.All.Where(m => m.LocalName == "table" || m.LocalName == "center");
            foreach (IElement table in tableLabListItemsLinq)
            {
                var blueListItemsLinq = table.QuerySelectorAll(" ");
                if (blueListItemsLinq.Count() == 0)
                {
                    blueListItemsLinq = table.QuerySelectorAll("img");
                }
                if (blueListItemsLinq.Count() != 0)
                {
                    if (table.QuerySelectorAll("b").Where(m => m.TextContent.Contains("工步")).Count() == 1)
                    {
                        string gongbucaiji = "工步" + processesSequence.ToString();
                        if (table.QuerySelectorAll("b").Where(m => m.TextContent.Contains(gongbucaiji)).Count() == 1)
                        {
                            table.ClassName += " processstep";
                            continue;
                        }
                        else
                        {
                            throw new UserFriendlyException("工序" + processesSequence.ToString() + " 有工步加粗字符！");
                        }
                    }
                    foreach (var item in tableClassNameList)
                    {
                        if (table.QuerySelectorAll("td").Count() > 0)//Children("P").Children("span").
                        {
                            if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(item)).Count() == 1)
                            {
                                //增加标签
                                AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                break;
                            }
                        }
                        else
                        {
                            if (item == "进箱舱登记表")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 进箱（舱）登记表") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (item == "整流罩星箭分离弹簧压缩数据记录表")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 整流罩/星箭分离弹簧压缩数据记录表") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (item == "管路活门气密点检查记录表皂泡法")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 管路活门气密点检查记录表（皂泡法）") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (item == "管路活门气密点检查记录表氦质谱法")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 管路活门气密点检查记录表（氦质谱法）") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (item == "电缆插头防水防热记录表")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 电缆（插头）防水（防热）记录表") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" " + item) && m.ClassList.Contains("FieldTitle")).Count() == 1)
                            {
                                AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                break;
                            }
                        }
                    }
                    if (table.QuerySelectorAll("a").Children("img").Count() > 0)
                    {
                        if (table.QuerySelectorAll("p").Where(m => m.TextContent.Contains("图")).Count() == 1)
                        {
                            var newGuidChart = Guid.NewGuid().ToString();
                            var pChart = document.CreateElement("tubiao");
                            pChart.TextContent = newGuidChart;
                            table.Insert(AdjacentPosition.BeforeBegin, pChart.ToHtml());
                            table.Remove();
                            var imghtml = table.ToHtml();

                            //更改图片src
                            string a, p, c;
                            GetImgSrc(imghtml, out a, out p, out c);
                            //string url= @"http://10.20.253.10:4027/DownloadIMG/";
                            var url= DownLoadIMG(imghtml,techniqueName);
                            a = c + "src=\"" + url.Url + ".png" + "\" border=\"0\">";

                            var html = a + "<p>" + p + "</p>";

                            tableHtmlList.Add(newGuidChart, html);
                            continue;
                        }
                    }
                }
                #region 原来
                //switch (GetTableType(table, tableClassNameList))
                //{
                //    case TableType.普通表格:
                //        break;
                //    case TableType.力矩复校记录表:
                //        var newGuidMomentRecord = Guid.NewGuid().ToString();

                //        var pMomentRecord = document.CreateElement("momentrecordtable");
                //        pMomentRecord.TextContent = newGuidMomentRecord;

                //        table.Insert(AdjacentPosition.BeforeBegin, pMomentRecord.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidMomentRecord, table.ToHtml());
                //        break;
                //    case TableType.通用力矩记录表:
                //        var newGuidMoment = Guid.NewGuid().ToString();

                //        var pMoment = document.CreateElement("momenttable");
                //        pMoment.TextContent = newGuidMoment;

                //        table.Insert(AdjacentPosition.BeforeBegin, pMoment.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidMoment, table.ToHtml());
                //        break;
                //    case TableType.插头状态检查表:
                //        var newGuidPlugState = Guid.NewGuid().ToString();

                //        var pPlugState = document.CreateElement("plugstatetable");
                //        pPlugState.TextContent = newGuidPlugState;

                //        table.Insert(AdjacentPosition.BeforeBegin, pPlugState.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidPlugState, table.ToHtml());
                //        break;
                //    case TableType.产品接地状态检查记录表:
                //        var newGuidProductGrounding = Guid.NewGuid().ToString();

                //        var pProductGrounding = document.CreateElement("productgroundingtable");
                //        pProductGrounding.TextContent = newGuidProductGrounding;

                //        table.Insert(AdjacentPosition.BeforeBegin, pProductGrounding.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidProductGrounding, table.ToHtml());
                //        break;
                //    case TableType.强制检验点记录表:
                //        var newGuidMandatoryInspection = Guid.NewGuid().ToString();

                //        var pMandatoryInspection = document.CreateElement("mandatoryinspectiontable");
                //        pMandatoryInspection.TextContent = newGuidMandatoryInspection;

                //        table.Insert(AdjacentPosition.BeforeBegin, pMandatoryInspection.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidMandatoryInspection, table.ToHtml());
                //        break;
                //    case TableType.状态检查记录表:
                //        var newGuidStatusCheck = Guid.NewGuid().ToString();

                //        var pStatusCheck = document.CreateElement("statuschecktable");
                //        pStatusCheck.TextContent = newGuidStatusCheck;

                //        table.Insert(AdjacentPosition.BeforeBegin, pStatusCheck.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidStatusCheck, table.ToHtml());
                //        break;
                //    case TableType.舱口盖状态检查记录表:
                //        var newGuidHatchState = Guid.NewGuid().ToString();

                //        var pHatchState = document.CreateElement("hatchstatetable");
                //        pHatchState.TextContent = newGuidHatchState;

                //        table.Insert(AdjacentPosition.BeforeBegin, pHatchState.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidHatchState, table.ToHtml());
                //        break;
                //    case TableType.舱口盖开闭测试记录表:
                //        var newGuidHatch = Guid.NewGuid().ToString();

                //        var pHatch = document.CreateElement("hatchtable");
                //        pHatch.TextContent = newGuidHatch;

                //        table.Insert(AdjacentPosition.BeforeBegin, pHatch.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidHatch, table.ToHtml());
                //        break;
                //    case TableType.传感器变换器对应关系记录表:
                //        var newGuidSensorRecord = Guid.NewGuid().ToString();

                //        var pSensorRecord = document.CreateElement("sensorrecordtable");
                //        pSensorRecord.TextContent = newGuidSensorRecord;

                //        table.Insert(AdjacentPosition.BeforeBegin, pSensorRecord.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidSensorRecord, table.ToHtml());
                //        break;

                //    //case TableType.记录表:
                //    //    var newGuid = Guid.NewGuid().ToString();

                //    //    var j = document.CreateElement("recordtable");
                //    //    j.TextContent = newGuid;

                //    //    table.Insert(AdjacentPosition.BeforeBegin, j.ToHtml());
                //    //    table.Remove();

                //    //    tableHtmlList.Add(newGuid, table.ToHtml());
                //    //    break;
                //    case TableType.通用多媒体记录表:
                //        var newGuidMedia = Guid.NewGuid().ToString();

                //        var pMedia = document.CreateElement("multimediatable");
                //        pMedia.TextContent = newGuidMedia;

                //        table.Insert(AdjacentPosition.BeforeBegin, pMedia.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidMedia, table.ToHtml());
                //        break;
                //    case TableType.图:
                //        var newGuidChart = Guid.NewGuid().ToString();

                //        var pChart = document.CreateElement("chartimg");
                //        pChart.TextContent = newGuidChart;

                //        table.Insert(AdjacentPosition.BeforeBegin, pChart.ToHtml());
                //        table.Remove();
                //        var imghtml = table.ToHtml();
                //        var trs = @"(?<=<a[^>]*?[^>]*?>)([\s\S]+?)(?=</a>)";
                //        var a = Regex.Matches(imghtml, trs).Cast<Match>().Select(mx => mx.Groups[0].Value.Trim().TrimStart().TrimEnd()).FirstOrDefault();

                //        var trp = @"(?<=<p[^>]*?[^>]*?>)([\s\S]+?)(?=</p>)";
                //        var p = Regex.Matches(imghtml, trp).Cast<Match>().Select(mx => mx.Groups[0].Value.Trim().TrimStart().TrimEnd()).FirstOrDefault();

                //        string c = a.Remove(a.LastIndexOf("src=\""));
                //        a = c + "src=\"../../tech/" + p + ".png" + "\" border=\"0\">";

                //        var html = a + "<p>" + p + "</p>";

                //        tableHtmlList.Add(newGuidChart, html);
                //        break;
                //    case TableType.装入件明细:
                //        var newGuidLoad = Guid.NewGuid().ToString();

                //        var pLoad = document.CreateElement("loadpiecetable");
                //        pLoad.TextContent = newGuidLoad;

                //        table.Insert(AdjacentPosition.BeforeBegin, pLoad.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidLoad, table.ToHtml());
                //        break;

                //    case TableType.视频:
                //        var newGuidVideo = Guid.NewGuid().ToString();

                //        var pVideo = document.CreateElement("videotable");
                //        pVideo.TextContent = newGuidVideo;

                //        table.Insert(AdjacentPosition.BeforeBegin, pVideo.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidVideo, table.ToHtml());
                //        break;
                //    case TableType.制造资源:
                //        var newGuidZZResources = Guid.NewGuid().ToString();

                //        var pZZResources = document.CreateElement("zzresourcestable");
                //        pZZResources.TextContent = newGuidZZResources;

                //        table.Insert(AdjacentPosition.BeforeBegin, pZZResources.ToHtml());
                //        table.Remove();

                //        tableHtmlList.Add(newGuidZZResources, table.ToHtml());
                //        break;
                //    case TableType.质量控制记录表:
                //    case TableType.工步签署表:
                //        var controtable = document.CreateElement("controlrecordtable");

                //        table.Insert(AdjacentPosition.BeforeBegin, controtable.ToHtml());
                //        table.Remove();
                //        break;
                //    case TableType.工步表:

                //        table.ClassName += " processstep";
                //        break;
                //}
                #endregion
            }
            //将所有识别为工步的加粗字体添加工步编号
            string gongbucaiji2 = "工步" + processesSequence.ToString() + "-";
            var stepLabListItemsLinq = document.All.Where(m => m.LocalName == "b" && m.TextContent.Contains(gongbucaiji2));

            //var stepLabListItemsLinq = document.All.Where(m => m.LocalName == "b" && m.TextContent.Contains("工步"));
            foreach (var step in stepLabListItemsLinq)
			{
				step.Id = Guid.NewGuid().ToString();
			}
			return document.ToHtml();

        }

        public static string ConvertHtmlLocal(string htmlString, string techniqueName, List<string> tableClassNameList, bool getWokrStep, ref Dictionary<string, string> tableHtmlList)
        {
            var context = BrowsingContext.New();
            var document = context.OpenAsync(req => req.Content(htmlString)).Result;
            var tableLabListItemsLinq = document.All.Where(m => m.LocalName == "table" || m.LocalName == "center");
            foreach (IElement table in tableLabListItemsLinq)
            {
                var blueListItemsLinq = table.QuerySelectorAll(" ");
                if (blueListItemsLinq.Count() == 0)
                {
                    blueListItemsLinq = table.QuerySelectorAll("img");
                }
                if (blueListItemsLinq.Count() != 0)
                {
                    if (table.QuerySelectorAll("b").Where(m => m.TextContent.Contains("工步")).Count() == 1)
                    {
                        table.ClassName += " processstep";
                        continue;
                    }
                    foreach (var item in tableClassNameList)
                    {
                        if (table.QuerySelectorAll("td").Count() > 0) //.Children("P").Children("span")
                        {
                            if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(item)).Count() == 1)
                            {
                                //增加标签
                                AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                break;
                            }

                        }
                        else
                        {
                            if (item == "进箱舱登记表")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 进箱（舱）登记表") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (item == "整流罩星箭分离弹簧压缩数据记录表")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 整流罩/星箭分离弹簧压缩数据记录表") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (item == "管路活门气密点检查记录表皂泡法")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 管路活门气密点检查记录表（皂泡法）") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (item == "管路活门气密点检查记录表氦质谱法")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 管路活门气密点检查记录表（氦质谱法）") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (item == "电缆插头防水防热记录表")
                            {
                                if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" 电缆（插头）防水（防热）记录表") && m.ClassList.Contains("FieldTitle")).Count() == 1)
                                {
                                    AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                    break;
                                }
                            }
                            if (table.QuerySelectorAll("td").Where(m => m.TextContent.Contains(" " + item) && m.ClassList.Contains("FieldTitle")).Count() == 1)
                            {
                                AddLabelElement(tableHtmlList, document, table, item, getWokrStep);
                                break;
                            }
                        }
                    }
                    if (table.QuerySelectorAll("a").Children("img").Count() > 0)
                    {
                        if (table.QuerySelectorAll("p").Where(m => m.TextContent.Contains("图")).Count() == 1)
                        {
                            var newGuidChart = Guid.NewGuid().ToString();
                            var pChart = document.CreateElement("tubiao");
                            pChart.TextContent = newGuidChart;
                            table.Insert(AdjacentPosition.BeforeBegin, pChart.ToHtml());
                            table.Remove();
                            var imghtml = table.ToHtml();
                           
                            //更改图片src
                            string a, p, c;
                            GetImgSrc(imghtml, out a, out p, out c);

                            string url = "../DownLoadFileRootPath/";
                            a = c + "src=\"" + url + techniqueName + "/" + p + ".jpg" + "\" border=\"0\">";

                            var html = a + "<p>" + p + "</p>";

                            tableHtmlList.Add(newGuidChart, html);
                            continue;
                        }
                    }
                }
            }
            //将所有识别为工步的加粗字体添加工步编号
            var stepLabListItemsLinq = document.All.Where(m => m.LocalName == "b" && m.TextContent.Contains("工步"));
            foreach (var step in stepLabListItemsLinq)
            {
                step.Id = Guid.NewGuid().ToString();
            }
            return document.ToHtml();

        }


        private static void GetImgSrc(string imghtml, out string a, out string p, out string c)
        {
            var trs = @"(?<=<a[^>]*?[^>]*?>)([\s\S]+?)(?=</a>)";
            a = Regex.Matches(imghtml, trs).Cast<Match>().Select(mx => mx.Groups[0].Value.Trim().TrimStart().TrimEnd()).FirstOrDefault();
            var trp = @"(?<=<p[^>]*?[^>]*?>)([\s\S]+?)(?=</p>)";
            p = Regex.Matches(imghtml, trp).Cast<Match>().Select(mx => mx.Groups[0].Value.Trim().TrimStart().TrimEnd()).FirstOrDefault();
            c = a.Remove(a.LastIndexOf("src=\""));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tableHtmlList"></param>
        /// <param name="document"></param>
        /// <param name="table"></param>
        /// <param name="newElementName"></param>
        private static void AddLabelElement(Dictionary<string, string> tableHtmlList, IDocument document, IElement table, string newElementName, bool getWokrStep)
        {
            var newGuidRecord = Guid.NewGuid().ToString();

            var pRecord = document.CreateElement(ConvertToPinYin.GetTotalPingYin(newElementName));
            pRecord.TextContent = "";
            if (getWokrStep)
            {
                pRecord.TextContent = newGuidRecord;
            }
            table.Insert(AdjacentPosition.BeforeBegin, pRecord.ToHtml());
            table.Remove();

            tableHtmlList.Add(newGuidRecord, table.ToHtml());
        }

        public static ImgInfo DownLoadIMG(string classTable, string code)
        {
            HtmlDocument doc = new HtmlDocument();
            WebClient wc = new WebClient();
            doc.LoadHtml(classTable);
            var appsettingsjson = JObject.Parse(File.ReadAllText("appsettings.json"));
            var app = (JObject)appsettingsjson["App"];
            var downLoadFileRootPath = app["DownLoadFileRootPath"];//DownLoad
            string filesavePath = Environment.CurrentDirectory + "/wwwroot/" + downLoadFileRootPath + "/" + code;
            string path="../"+ downLoadFileRootPath + "/" + code;
            if (!Directory.Exists(filesavePath))
            {
                Directory.CreateDirectory(filesavePath);

            }
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//a/img");
            var url = node.Attributes["src"].Value;

            if (url.IndexOf("https:") == -1 && url.IndexOf("http:") == -1)
            {
                url = "http://10.20.254.53:8080" + url;
            }
            var imgName = Guid.NewGuid().ToString("D");
            //下载图片
            try
            {
                wc.DownloadFile(url, filesavePath + "/" + imgName + ".png");
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
                Console.WriteLine(url);
            }
            return new ImgInfo()
            {
                Url = path + "/" + imgName,//"http://10.20.254.10:7011/" +
                ImgName = imgName
            };
        }
        public class ImgInfo
        {
            public string Url { get; set; }
            public string ImgName { get; set; }
        }
    }
}
